//
//  MFDataCenter.swift
//  mfmm
//
//  Created by lxl on 2018/5/24.
//  Copyright © 2018年 MF. All rights reserved.
//

import UIKit
import Alamofire
import DaisyNet

class SDataCenter: NSObject {
    static let shared = SDataCenter()
    var isSkip = false
    func sendVertifyCode(type : Int , phoneNum : String,resultWith:@escaping (_ isSucess:Bool)->()) {
        var params = [String : Any]()
        params["usageMode"] = type
        params["verifyType"] = 1
        params["verifyValue"] = phoneNum

        SPostJsonDataWithUrl(str_url: "api/services/app/Account/SendSecurityCodeAsync", params: params) { (responseData, isSuccess) in
            resultWith(isSuccess)

        }
    }

    func SDeleteDataWithUrl(str_url:String,params:[String:Any]?,isCache : Bool? = false,dynaParams:Parameters? = nil,resultWith: @escaping (_ resopnseData:Any,_ isSucess:Bool)->()) -> Void {
        
        
        
        SRequestJsonDataWithUrl(str_url: str_url, params: params, isCache: isCache!, method: .delete, dynaParams: dynaParams) { (data, sucess) in
            resultWith(data,sucess!)
        }
    }
    /// Get请求方法
    /// - Parameters:
    ///   - str_url: 请求地址
    ///   - params: 所需参数
    ///   - isCache: 是否要缓存
    ///   - dynaParams: 注意： 如果参数中带有时间戳、token等变化的参数，这些参数需要写在dynamicParams参数中，避免无法读取缓存
    ///   - resultWith: 返回结果
    func SGetJsonDataWithUrl(str_url:String,params:[String:Any]?,isCache : Bool? = false,dynaParams:Parameters? = nil,resultWith: @escaping (_ resopnseData:Any,_ isSucess:Bool)->()) -> Void {
   
   
        
        SRequestJsonDataWithUrl(str_url: str_url, params: params, isCache: isCache!, method: .get, dynaParams: dynaParams) { (data, sucess) in
            resultWith(data,sucess!)
        }
    }
    func SPostJsonDataWithUrl(str_url:String,params:[String:Any]?,isCache : Bool? = false,dynaParams:Parameters? = nil,resultWith: @escaping (_ resopnseData:Any,_ isSucess:Bool)->()) -> Void {
//        let url = BASE_URL + str_url
//
//        var header = [String : String]()
//        if UserInfo.getTheUserToken().count > 0{
//            header["Authorization"] = "Bearer " + UserInfo.getTheUserToken()
//        }
//        Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: header).responseJSON { (responseData) in
//            print(responseData)
//        }

        SRequestJsonDataWithUrl(str_url: str_url, params: params, isCache: isCache!, method: .post, dynaParams: dynaParams) { (data, sucess) in
            resultWith(data,sucess!)
        }
    }
    
    // MARK: -此为请求的原始方法
    fileprivate func SRequestJsonDataWithUrl(str_url:String,params:[String:Any]?,isCache : Bool,method:HTTPMethod,dynaParams:Parameters? = nil,requestResult:@escaping (Any, Bool?)->()) {
    
     
        let url = BASE_URL + str_url
        var tURL : String?
        if method == .get {
             tURL = parmarsCoding(method: method, URL: url, parmars: params)
        }else{
             tURL = url
        }
//        let tURL = parmarsCoding(method: method, URL: url, parmars: params!)
//        let tURL = url
        var header = [String : String]()
        if UserInfo.getTheUserToken().count > 0{
            header["Authorization"] = "Bearer " + UserInfo.getTheUserToken()
        }

        print("当前的URL: \(tURL!)")
        
        
        DaisyNet.request(tURL!,method: method, params: method == .get ? nil : params, dynamicParams: dynaParams,encoding: method == .post ? JSONEncoding.default : URLEncoding.default ,headers:header).cache(isCache).responseCacheAndJson{ (responseData) in
        
//        DaisyNet.request(tURL, method: method, params: method == .get ? nil : parame, dynamicParams: dynaParams, encoding: JSONEncoding.default, headers: nil).cache(isCache).responseCacheAndJson { (responseData) in
            print("请求结束")
//            SProgressHUD.hide()
            switch responseData.result {
            case .success(_)://不管有没有网，只要有缓存就先取缓存
                if responseData.isCacheData {
                    print("缓存")
                } else {
                    print("网络")
                }
                let object = responseData.result.value
                
                //
                if let jsonObject = object as? NSDictionary{
                    
                    if let success = jsonObject["success"]{
                        if success as! Int == 1{
                            let resultObj = jsonObject["result"]
                            
                            requestResult(resultObj as Any ,true)
                        }else{
                            let errorObj = jsonObject["error"]
                            if errorObj != nil && errorObj is [String : Any]{
                                let error = (errorObj as! [String : Any])["message"]
                                ProgressHUD.showMsgWithoutView(error as? String)
                                requestResult(error as Any ,false)
                            }else{
                                requestResult("获取失败" ,false)
                            }
                        }
                    }else if jsonObject.count > 0{//暂时的，最后都要去掉，目前没有成功失败状态判断
                        requestResult(jsonObject as Any ,true)
                    }else{
                        requestResult("无返回状态" ,false)

                    }
                 
                }else if let jsonArr = object as? NSArray{//暂时的，最后都要去掉
                    requestResult(jsonArr as Any ,true)
                }else{
                    requestResult("数据类型不识别" ,false)
                }
                
             
            case .failure(let error):
                print(error)
                ProgressHUD.showMsgWithoutView("请求失败")

                requestResult("请求失败" as AnyObject,false)
//                当前的URL: http://maosheng.csproj.com/api/services/app/Blog/GetMyBlogCommentPagingListAsync?PageIndex=1&PageSize=10

            }
           
            

    }


    }
    
    
    
    func upLoadImageRequest(urlString : String, params:[String:String], data: [Data], name: [String],success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()){
        
        let headers = ["content-type":"multipart/form-data"]
        
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                //666多张图片上传
                let flag = params["flag"]
                let userId = params["userId"]
                
                multipartFormData.append((flag?.data(using: String.Encoding.utf8)!)!, withName: "flag")
                multipartFormData.append( (userId?.data(using: String.Encoding.utf8)!)!, withName: "userId")
                
                for i in 0..<data.count {
                    multipartFormData.append(data[i], withName: "upload", fileName: name[i], mimeType: "image/png")
                }
        },
            to: urlString,
            headers: headers,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        if let value = response.result.value as? [String: AnyObject]{
                            success(value)
//                            let json = JSON(value)
//                            PrintLog(json)
                        }
                    }
                case .failure(let encodingError): break
//                    PrintLog(encodingError)
//                    failture(encodingError)
                }
        }
        )
    }

//    //MARK:-取消请求
//    func cancleRequest() -> Void {
//        var parame = params
//        parame?["version"] = UtilTool.getCurrentLocalVersion()
//        parame?["deviceModel"] = UtilTool.deviceString()
//        parame?["osVersion"] = UtilTool.getIOSVersion()
//        parame?["resolution"] = UtilTool.getDeviceResolvingPower()
//        parame?["channel"] = "appstore"
//        let url = BASE_URL + str_url
//
//        let tURL = parmarsCoding(method: method, URL: url, parmars: parame!)
//        DaisyNet.cancel(tURL)
//
//    }
    //MARK:字典转为字符串拼接
    private func parmarsCoding(method:HTTPMethod,URL:String,parmars:[String:Any]?) -> String {
        if parmars == nil{
            return URL
        }
        if method == .get {
            let keys = parmars!.keys
            var url = "\(URL)"
            var isFirst = true
            for item in keys {
                let key = item
                
                
                let value = parmars![key]
                if key.contains("&coding") == true {
                    url = isFirst == true ? "\(url)?\(key.components(separatedBy:"&coding")[0])=" : "\(url)&\(key.components(separatedBy:"&coding")[0])="
                    isFirst = false
                    do
                    {
                        let josnData = try JSONSerialization.data(withJSONObject: value!, options: .prettyPrinted)
                        var str = String(data: josnData, encoding: .utf8)
                        str = str?.replacingOccurrences(of: "\n", with: "")
                        let experCode = str?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)
                        url = "\(url)\(experCode!)"
                    }catch {
                        return url
                    }
                    
                } else {
                    url = isFirst == true ? "\(url)?\(key)=" : "\(url)&\(key)="
                    isFirst = false
                    url = "\(url)\(value!)"
                }
                
            }
            return url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        }
        return URL
    }
    
    
    
}
